package cn.ldw.test;

import java.util.Arrays;

public class HeadSort {
    public static void main(String[] args) {
        int[] nums = new int[] {5, 1, 2, 6, 9, 3};
        sort(nums);
        System.out.println(Arrays.toString(nums));
    }

    //构建大顶堆
    public static void sort(int[] nums) {
        int len = nums.length;
        for(int i = len / 2 - 1; i >= 0; i--) {
            adjustHead(nums, i, len);
        }
        for(int j = len - 1; j > 0; j--) {
            swap(nums, 0, j);
            adjustHead(nums, 0, j);
        }
    }
    //调整堆
    public static void  adjustHead(int[] nums, int i, int len) {
        int temp = nums[i];
        for(int j = i * 2 + 1; j < len; j = j * 2 + 1) {
            if(j + 1 < len && nums[j] < nums[j+1]) {
                j++;
            }
            if(nums[j] > temp) {
                nums[i] = nums[j];
                i = j;
            }
            else {
                break;
            }
        }
        nums[i] = temp;
    }

    //交换
    public static void swap(int []arr,int a ,int b){
        int temp=arr[a];
        arr[a] = arr[b];
        arr[b] = temp;
    }
}
